# reference: 20190501_线性回归.ipynb
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# section 4.1.1
#the excel "Body-Fat.xls" path
path = "./data/Body-Fat.xls"
data_df = pd.read_excel(path)
part_data_df = data_df[["hipline","weight"]] #excel use english title
plt.scatter(part_data_df['hipline'],part_data_df['weight'])
plt.xlabel("hipline")
plt.ylabel("weight")

plt.savefig('4.1-linearRegression.png')

#section 4.1.3
x_df = part_data_df[['hipline']].copy()
x_df['cons'] =1
left_data = np.linalg.inv(np.dot(x_df.T, x_df))
right_data = np.dot(x_df.T, part_data_df['weight'])
a,b = np.dot(left_data, right_data)
print('a=',a,'b=',b)

plt.scatter(part_data_df['hipline'], part_data_df['weight'])
plt.plot(part_data_df['hipline'], part_data_df['hipline'] * a + b, 'r-')
plt.xlabel("hipline")
plt.ylabel("weight")
plt.annotate("$\hat{y} = 1.75 x - 93.63$", xy=(130,150), 
             xytext=(100, 150), arrowprops=dict(facecolor='black', shrink=0.01))
plt.grid(True)
plt.savefig("4.2-linearRegression.png")
plt.show()
#y_predict = part_data_df['hipline'] * a + b
#y_real = part_data_df['weight']
#(y_real-y_predict).mean()
#np.sqrt(((y_real-y_predict) ** 2).mean())
#1 - sum((y_real-y_predict) ** 2)/ sum((part_data_df['weight'] - part_data_df['weight'].sum()) ** 2)